/**
 * @file      : main.c
 * @brief     : 程序入口源文件
 * @author    : huenrong (huenrong1028@gmail.com)
 * @date      : 2020-09-06 15:02:04
 *
 * @copyright : Copyright (c) 2020  胡恩荣
 *
 */

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include "./list/list.h"

struct list_node g_test_list = {0};
pthread_mutex_t g_test_list_mutex;

/**
 * @brief  插入链表线程
 */
void *insert_list_thread(void);

/**
 * @brief  读取链表线程
 */
void *read_list_thread(void);

int main(int argc, char *argv[])
{
    int ret = -1;
    pthread_t insert_list_thread_id;
    pthread_t read_list_thread_id;
    struct list_data test_data = {0};

    // 初始化链表
    ret = init_list(&g_test_list, &g_test_list_mutex);
    if (0 != ret)
    {
        printf("init list fail\n");
    }

    // 创建链表读取线程
    ret = pthread_create(&insert_list_thread_id, NULL,
                         (void *)insert_list_thread,
                         NULL);
    // 线程创建成功
    if (0 == ret)
    {
        // 线程分离, 结束时自动回收资源
        pthread_detach(insert_list_thread_id);
    }

    // 创建链表读取线程
    ret = pthread_create(&read_list_thread_id, NULL,
                         (void *)read_list_thread,
                         NULL);
    // 线程创建成功
    if (0 == ret)
    {
        // 线程分离, 结束时自动回收资源
        pthread_detach(read_list_thread_id);
    }

    // 链表插入
    while (1)
    {
        test_data.id = 1;
        test_data.time = 2;

        printf("111\n");
        ret = insert_tail_list(&g_test_list_mutex, &g_test_list, test_data);
        printf("222\n");
        if (0 != ret)
        {
            printf("insert data fail\n");
        }

        usleep(10 * 1000);
    }

    return 0;
}

/**
 * @brief  插入链表线程
 */
void *insert_list_thread(void)
{
    int ret = -1;
    struct list_data test_data = {0};

    while (1)
    {
        test_data.id = 1;
        test_data.time = 2;

        printf("333\n");
        ret = insert_tail_list(&g_test_list_mutex, &g_test_list, test_data);
        printf("444\n");
        if (0 != ret)
        {
            printf("insert data fail\n");
        }

        usleep(10 * 1000);
    }
}

/**
 * @brief  读取链表线程
 */
void *read_list_thread(void)
{
    struct list_data dst_data = {0};
    struct list_node *find_data = NULL;

    while (1)
    {

        dst_data.id = 1;
        dst_data.time = 2;

        find_data = find_node_list(&g_test_list_mutex, &g_test_list, dst_data);
        if ((NULL != find_data))
        {
            printf("ccc\n");
            delete_node_list(&g_test_list_mutex, &g_test_list, find_data->data);
            printf("eee\n");
        }

        usleep(20 * 1000);
    }
}
